import { defineStore } from 'pinia'
import axios from 'axios'

export const useNotificationStore = defineStore('notification', {
  state: () => ({
    unreadCount: 0,
    notifications: [],
    showPopover: false
  }),
  
  actions: {
    async fetchUnreadCount() {
      try {
        const { data } = await axios.get('/api/notifications/unread-count')
        this.unreadCount = data
        console.log('未读消息数:', data)
      } catch (error) {
        console.error('获取未读消息数失败:', error)
      }
    },
    
    async fetchNotifications(page = 0, size = 5) {
      try {
        const { data } = await axios.get('/api/notifications', {
          params: { page, size, isRead: false }
        })
        this.notifications = data.content
        this.unreadCount = data.totalElements
        console.log('获取消息列表:', data)
      } catch (error) {
        console.error('获取消息列表失败:', error)
      }
    },
    
    async markAsRead(ids) {
      try {
        await axios.post('/api/notifications/mark-read', { ids })
        // 标记已读后，重新获取未读数
        await this.fetchUnreadCount()
      } catch (error) {
        console.error('标记已读失败:', error)
        throw error
      }
    },
    
    async deleteNotifications(ids) {
      try {
        await axios.delete('/api/notifications', { data: { ids } })
        // 删除后，重新获取未读数
        await this.fetchUnreadCount()
      } catch (error) {
        console.error('删除消息失败:', error)
        throw error
      }
    }
  }
}) 